import mongoose, { Document, Schema } from 'mongoose';

export interface IUserCoupon extends Document {
  user: mongoose.Types.ObjectId;
  coupon: mongoose.Types.ObjectId;
  isUsed: boolean;
  usedAt: Date;
  order: mongoose.Types.ObjectId;
  expireAt: Date;
  createdAt: Date;
  updatedAt: Date;
}

const UserCouponSchema: Schema = new Schema(
  {
    user: {
      type: Schema.Types.ObjectId,
      ref: 'User',
      required: true,
    },
    coupon: {
      type: Schema.Types.ObjectId,
      ref: 'Coupon',
      required: true,
    },
    isUsed: {
      type: Boolean,
      default: false,
    },
    usedAt: {
      type: Date,
    },
    order: {
      type: Schema.Types.ObjectId,
      ref: 'Order',
    },
    expireAt: {
      type: Date,
      required: true,
    },
  },
  {
    timestamps: true,
  }
);

// 创建复合索引，一个用户一个优惠券只能领取一次
UserCouponSchema.index({ user: 1, coupon: 1 }, { unique: true });
UserCouponSchema.index({ user: 1, isUsed: 1 });
UserCouponSchema.index({ expireAt: 1 });

export default mongoose.model<IUserCoupon>('UserCoupon', UserCouponSchema); 